'use strict';

/* 
{
    uuid: {
        type: STRING(38),
        allowNull: false,
        primaryKey: true,
        defaultValue: UUIDV4,
      },
      created_at: DATE,
      updated_at: DATE,
      created_use_uuid: {
        type: UUID,
        allowNull: true,
        references: {
          model: 'users',
          key: 'uuid',
        },
        onUpdate: 'cascade',
        onDelete: 'cascade',
      },
      name: {
        type: STRING(128),
        allowNull: false,
        comment: "商品品类名",
      },
      intro: {
        type: STRING(255),
        allowNull: true,
        comment: "商品品类介绍",
      },
      parent_type_uuid: {
        type: STRING(38),
        allowNull: true,
        comment: "父类商品"
      },
      deleted: {
        type: ENUM('0', '1'),
        allowNull: false,
      }
  }

 */

module.exports = app => {
  const { Sequelize, model } = app;
  const { Op } = Sequelize;
  const { INTEGER, BIGINT, ENUM, DATE, STRING, UUIDV4, UUID } = Sequelize;
  const goodsTypeSchema = require('../schema/goodsType')(app);  // 注意，导出的是一个方法返回表的列信息
  const GoodsType = model.define('goods_types', goodsTypeSchema);

  GoodsType.toggleDeleted = async uuid => {
    const goodstype =  await GoodsType.findByPk(uuid);
    goodstype.deleted = goodstype.deleted === '1' ? '0': '1';
    goodstype.save();
    return goodstype;      
  }

  GoodsType.saveNew = async (goodsType) => {
    const res = await GoodsType.create(goodsType)
    return res;
  }

  GoodsType.findOne = async (filter) => {
    const res = await GoodsType.find({ where: { ...filter }})
    return  res;
  }

  GoodsType.updateOne = async (goodsType) => {
    const { name, intro, price, imgs, uuid } =  goodsType;
    const updateField = { name, intro, price, imgs };
    const res = await GoodsType.update(updateField, {where:{uuid}})
    return res;
  }

  GoodsType.queryList = async (pagenation = {}, filter={}) => {
    const { page, pageSize } = pagenation;
    const condition = {
      offset: (page - 1)*pageSize || 0,
      limit: +pageSize || 20,
      where: filter
    }
    const list = await GoodsType.findAndCountAll(condition);
    return { page, pageSize, ...list };
  }

  return GoodsType;
}
